

#include <stdio.h>

#include "system.h"
#include "altera_avalon_pio_regs.h"
#include "alt_types.h"

#include "altera_avalon_pwm_routines.h"


void CHANGE_DIRECTION();

int main(void)

{

	unsigned int duty_cycle;
	int return_code = ALTERA_AVALON_PWM_OK;

	float desired_duty_cycle;


	//Initialize PWM and Check Return Code
	altera_avalon_pwm_init(PWM0_BASE,1,2047); // 50% duty Cycle with maximum frequency/1 (9kHz)
	altera_avalon_pwm_init(PWM1_BASE,1,2047);

	//Generate sign-magnitude pwm.
	altera_avalon_pwm_change_duty_cycle(PWM0_BASE, 1023);
	altera_avalon_pwm_locked_antiphase_mode(PWM0_BASE);
	altera_avalon_pwm_sign_magnitude_mode(PWM1_BASE);

	//Enable PWM and Check Return Code
	altera_avalon_pwm_enable(PWM0_BASE);
	altera_avalon_pwm_enable(PWM1_BASE);


	IOWR_ALTERA_AVALON_PIO_DATA(OUTPUT_PORT_B_BASE,0x06);
	printf("Start PWM..\n");

	while(1){
		//printf("%x\n",IORD_ALTERA_AVALON_PIO_DATA(OUTPUT_PORT_B_BASE));
		printf("Type duty cycle percentage :");
		scanf("%f",&desired_duty_cycle );

		if (desired_duty_cycle >= 100){
			altera_avalon_pwm_change_duty_cycle(PWM0_BASE, 4095);
			altera_avalon_pwm_change_duty_cycle(PWM1_BASE, 4095);
			}
		else {
			altera_avalon_pwm_change_duty_cycle(PWM0_BASE, (desired_duty_cycle/100.0)*4095);
			altera_avalon_pwm_change_duty_cycle(PWM1_BASE, (desired_duty_cycle/100.0)*4095);
			}

		CHANGE_DIRECTION();


	}
	return 0;
}


void CHANGE_DIRECTION(){
	int a = IORD_ALTERA_AVALON_PIO_DATA(OUTPUT_PORT_B_BASE);
	if (a==0x05) {
		IOWR_ALTERA_AVALON_PIO_DATA(OUTPUT_PORT_B_BASE,0x00);
		usleep(1000);
		//IOWR_ALTERA_AVALON_PIO_DATA(OUTPUT_PORT_B_BASE,0x0A);
		IOWR_ALTERA_AVALON_PIO_DATA(OUTPUT_PORT_B_BASE,0x06);
		printf("Pin 3 and Pin 5 are on.\n");
		}
	else{
		IOWR_ALTERA_AVALON_PIO_DATA(OUTPUT_PORT_B_BASE,0x00);
		usleep(1000);
		IOWR_ALTERA_AVALON_PIO_DATA(OUTPUT_PORT_B_BASE,0x06);
		printf("Pin 2 and Pin 4 are on.\n");
		}
	}

void GO_FORWARD(int duty_cycle){

	}

void GO_BACKWARD(int duty_cycle){

	}

void TURN_LEFT(int duty_cycle){

	}

void TURN_RIGHT(int duty_cycle){
	}
